﻿// Ban do
var map;

// Layer hien thi ket qua tim kiem
var showSearchResult;

// Cong cu do khoang cach, dien tich
var measureControls;

// control pgrouting
var controls, start, stop, result, parser;

OpenLayers.IMAGE_RELOAD_ATTEMPTS = 5;

var SinglePoint = OpenLayers.Class(OpenLayers.Handler.Point,
		{
			createFeature : function(pixel) {
				if (this.control.layer.features.length > 1) {
					this.control.layer
							.removeFeatures(this.control.layer.features);
				}
				OpenLayers.Handler.Point.prototype.createFeature.apply(this,
						arguments);
			}
		});

var start_style = OpenLayers.Util.applyDefaults({
	externalGraphic : "images/start.png",
	graphicWidth : 18,
	graphicHeight : 26,
	graphicYOffset : -26,
	graphicOpacity : 1
}, OpenLayers.Feature.Vector.style['default']);

var stop_style = OpenLayers.Util.applyDefaults({
	externalGraphic : "images/stop.png",
	graphicWidth : 18,
	graphicHeight : 26,
	graphicYOffset : -26,
	graphicOpacity : 1
}, OpenLayers.Feature.Vector.style['default']);

var result_style = OpenLayers.Util.applyDefaults({
	strokeWidth : 3,
	strokeColor : "#ff0000",
	fillOpacity : 0
}, OpenLayers.Feature.Vector.style['default']);

// ham khoi tao ban do
function init() {
	// Creation of a custom panel with a ZoomBox control with the alwaysZoom
	// option sets to true
	OpenLayers.Control.CustomNavToolbar = OpenLayers.Class(
			OpenLayers.Control.Panel, {

				/**
				 * Constructor: OpenLayers.Control.NavToolbar Add our two
				 * mousedefaults controls.
				 * 
				 * Parameters: options - {Object} An optional object whose
				 * properties will be used to extend the control.
				 */

				initialize : function(options) {
					OpenLayers.Control.Panel.prototype.initialize.apply(this,
							[ options ]);
					this.addControls([ new OpenLayers.Control.Navigation(),
					// Here it come
					new OpenLayers.Control.ZoomBox({
						alwaysZoom : true
					}) ]);
					// To make the custom navtoolbar use the regular navtoolbar
					// style
					this.displayClass = 'olControlNavToolbar'
				},

				/**
				 * Method: draw calls the default draw, and then activates mouse
				 * defaults.
				 */
				draw : function() {
					var div = OpenLayers.Control.Panel.prototype.draw.apply(
							this, arguments);
					this.defaultControl = this.controls[0];
					return div;
				}
			});

	OpenLayers.ProxyHost = "control/proxy.php?url=";

	var bounds = new OpenLayers.Bounds(107.817883080344, 15.9140867740137,
			108.337590000029, 16.2251302357152
	// 508414.1875, 1766000.25,
	// 534872.6875, 1786073.875
	);

	var options = {
		controls : [ new OpenLayers.Control.Navigation(),
				new OpenLayers.Control.PanZoomBar(),
				new OpenLayers.Control.LayerSwitcher({
					'ascending' : true
				}), new OpenLayers.Control.MousePosition(),
				new OpenLayers.Control.ScaleLine(),
				new OpenLayers.Control.Permalink(),
				new OpenLayers.Control.OverviewMap() ],
		numZoomLevels : 10,
		maxExtent : bounds,
		maxResolution : 0.0020301051550195,
		projection : "EPSG:4326",
		units : 'degrees'
	};
	map = new OpenLayers.Map('map-element', options);

	var layer_QuanHuyen = new OpenLayers.Layer.WMS('Quan Huyen',
			'http://localhost:8081/geoserver/DATN/wms', {
				layers : 'DATN:DNQH',
				styles : '',
				transparent : 'true',
			}, {
				singleTile : true,
				ratio : 1,
				isBaseLayer : true,
				yx : {
					'EPSG:4326' : false
				}
			});
	map.addLayer(layer_QuanHuyen);

	var layer_Giaothong = new OpenLayers.Layer.WMS('Giao Thông',
			'http://localhost:8081/geoserver/DATN/wms', {
				layers : 'DATN:dngt',
				styles : '',
				transparent : 'true',
			}, {
				singleTile : true,
				ratio : 1,
				yx : {
					'EPSG:4326' : false
				}
			});
	map.addLayer(layer_Giaothong);

	var layer_Hotel = new OpenLayers.Layer.WMS('Khách Sạn',
			'http://localhost:8081/geoserver/DATN/wms', {
				layers : 'DATN:dnhotel',
				styles : '',
				transparent : 'true',
			}, {
				singleTile : true,
				ratio : 1,
				yx : {
					'EPSG:4326' : false
				}
			});
	map.addLayer(layer_Hotel);

	// Ho tro GetFeatureInfo
	map.events.register('click', map, function(e) {

		// document.getElementById('nodelist').innerHTML = "Đang lấy thông
		// tin... Vui lòng chờ...";
		// Lam tron toa do, tren Firefox toa do lay so thuc
		var x = parseInt(e.xy.x);
		var y = parseInt(e.xy.y);

		// Luu toa do x, y cua man hinh lai tren trang chu
		$("div#x").html(e.clientX);
		$("div#y").html(e.clientY);

		// Tao cau truy van cho dich vu GetFeatureInfo
		var url = map.layers[1].getFullRequestString({
			REQUEST : "GetFeatureInfo",
			EXCEPTIONS : "application/vnd.ogc.se_xml",
			BBOX : map.getExtent().toBBOX(),
			X : x,
			Y : y,
			INFO_FORMAT : 'application/vnd.ogc.gml',
			LAYERS : [ map.layers[2].params.LAYERS],
			QUERY_LAYERS : [ map.layers[2].params.LAYERS],
			FEATURE_COUNT : 1,
			WIDTH : map.size.w,
			HEIGHT : map.size.h
		}, "http://localhost:8081/geoserver/wms");
		OpenLayers.loadURL(url, '', this, setHTML, setHTML);
		OpenLayers.Event.stop(e);
	});

	// Cong cu do khoang cach, dien tich
	// (http://openlayers.org/dev/examples/measure.html)
	// Trang tri cac net ve khi do
	var sketchSymbolizers = {
		"Point" : {
			pointRadius : 4,
			graphicName : "square",
			fillColor : "white",
			fillOpacity : 1,
			strokeWidth : 1,
			strokeOpacity : 1,
			strokeColor : "#004422"
		},
		"Line" : {
			strokeWidth : 3,
			strokeOpacity : 1,
			strokeColor : "#11aa00",
			strokeDashstyle : "dash"
		},
		"Polygon" : {
			strokeWidth : 2,
			strokeOpacity : 1,
			strokeColor : "#11aa00",
			fillColor : "white",
			fillOpacity : 0.3
		}
	};
	// //////
	var sketchStyle = new OpenLayers.Style();
	sketchStyle.addRules([ new OpenLayers.Rule({
		symbolizer : sketchSymbolizers
	}) ]);
	var styleMap = new OpenLayers.StyleMap({
		"default" : sketchStyle
	});

	// allow testing of specific renderers via "?renderer=Canvas", etc
	var renderer = OpenLayers.Util.getParameters(window.location.href).renderer;
	renderer = (renderer) ? [ renderer ]
			: OpenLayers.Layer.Vector.prototype.renderers;

	measureControls = {
		line : new OpenLayers.Control.Measure(OpenLayers.Handler.Path, {
			persist : true,
			handlerOptions : {
				layerOptions : {
					renderers : renderer,
					styleMap : styleMap
				}
			}
		}),
		polygon : new OpenLayers.Control.Measure(OpenLayers.Handler.Polygon, {
			persist : true,
			handlerOptions : {
				layerOptions : {
					renderers : renderer,
					styleMap : styleMap
				}
			}
		})
	};
	var control;
	for ( var key in measureControls) {
		control = measureControls[key];
		control.events.on({
			"measure" : handleMeasurements,
			"measurepartial" : handleMeasurements
		});
		map.addControl(control);
	}

	// Tat che do do khoang cach khi khoi tao xong
	document.getElementById('noneToggle').checked = true;

	// Hien thi ket qua tim kiem
	// Style cho layer ket qua
	// TODO: Style for showSearchResult layer
	var showSearchResultStyle = OpenLayers.Util.applyDefaults({
		externalGraphic : "images/pink_marker.png",
		graphicWidth : 32,
		graphicHeight : 32,
		graphicYOffset : -26,
		graphicOpacity : 1,
		strokeWidth : 6,
		strokeColor : '#FF0004',
		strokeOpacity : 0.8
	}, OpenLayers.Feature.Vector.style['default']);

	// Layer hien ket qua
	showSearchResult = new OpenLayers.Layer.Vector("Kết quả tìm kiếm", {
		style : showSearchResultStyle,
		srs : 'EPSG:4326',
		displayInLayerSwitcher : false
	});

	map.addLayer(showSearchResult);

	/** ******Tim duong******** */

	start = new OpenLayers.Layer.Vector("Điểm bắt đầu", {
		style : start_style,
		displayInLayerSwitcher : false
	});
	stop = new OpenLayers.Layer.Vector("Điểm kết thúc", {
		style : stop_style,
		displayInLayerSwitcher : false
	});
	result = new OpenLayers.Layer.Vector("Kết quả tìm đường", {
		style : result_style
	});

	map.addLayers([ start, stop, result ]);

	// controls
	controls = {
		start : new OpenLayers.Control.DrawFeature(start, SinglePoint),
		stop : new OpenLayers.Control.DrawFeature(stop, SinglePoint)
	}

	for ( var key in controls) {
		map.addControl(controls[key]);
	}

	var panel = new OpenLayers.Control.CustomNavToolbar();
	map.addControl(panel);

	// if(!map.getCenter()){
	// map.zoomToMaxExtent();
	// }
	jump(16.0605112504215, 108.216668731851);

	// create a parser for WKT that we will get back
	// in the results XML
	parser = new OpenLayers.Format.WKT();

}

// focus ban do toi 1 diem dung lat, lon
function jump(lat, lon) {
	var zoom = 7;
	var lonLat = new OpenLayers.LonLat(lon, lat).transform(
			new OpenLayers.Projection("EPSG:4326"), // transform from WGS 1984
			map.getProjectionObject() // to Spherical Mercator Projection
	);
	map.setCenter(lonLat, zoom);
}

/** ******* Phan xu ly GetFeatureInfo ******* */
// sets the HTML provided into the nodelist element
function setHTML(response) {

	// Tao mot doi tuong GML
	var g = new OpenLayers.Format.GML();

	// Dung ham read doc gia tri tra ve va chuyen sang dang GML
	var features = g.read(response.responseText);

	// Dung Ajax lay thong tin doi tuong nho FID
	OpenLayers.loadURL("control/get_info.php?fid=" + features[0].fid + "&id=" + features[0].id, '', this,
			showInfo, showInfo);
};

// Hien thi thong tin len cua so Popup
function showInfo(response) {

	// Gan ket qua tra ve vao div#info
	$('div#info').html(response.responseText);

	// Lay toa do da luu tren trang chu
	var x = eval($("div#x").html());
	var y = eval($("div#y").html());

	// Hien Popup, zIndex = 1000 cho phep hien tren cung
	var $dialog = $('div#info').dialog({
		autoOpen : true,
		width : 'auto',
		position : [ x, y ],
		zIndex : 10000,
		title : 'Thông tin khách sạn'
	});
}

// Ham xu ly cho cong cu do khoang cach
function handleMeasurements(event) {
	var geometry = event.geometry;
	var units = event.units;
	var order = event.order;
	var measure = event.measure;
	var element = document.getElementById('measureResult');
	var out = "";
	if (order == 1) {
		out += "Tổng chiều dài: " + measure.toFixed(3) + " " + units;
	} else {
		out += "Diện tích: " + measure.toFixed(3) + " " + units + "<sup>2</"
				+ "sup>";
	}
	element.innerHTML = out;
}

// Ham xu ly chuyen doi qua lai giua cac cong cu do
function toggleControl(element) {
	for (key in measureControls) {
		var control = measureControls[key];
		if (element.value == key && element.checked) {
			control.activate();
		} else {
			control.deactivate();
		}
	}
}

/** ******* Phan xu ly tim duong **************** */

function routingToggleControl(element) {
	for (key in controls) {
		if (element.value == key && element.checked) {
			controls[key].activate();
		} else {
			controls[key].deactivate();
		}
	}
}

function compute() {
	var startPoint = start.features[0];
	var stopPoint = stop.features[0];

	if (startPoint && stopPoint) {

		OpenLayers.loadURL("control/ax_routing.php?startpoint="
				+ startPoint.geometry.x + " " + startPoint.geometry.y
				+ "&finalpoint=" + stopPoint.geometry.x + " "
				+ stopPoint.geometry.y + "&region=dngt&srid=4326", null, null,
				displayRoute, null);
	}
}

function displayRoute(response) {
	if (response && response.responseXML) {
		// erase the previous results
		result.removeFeatures(result.features);

		// parse the features
		var edges = response.responseXML.getElementsByTagName('edge');
		var features = [];
		for ( var i = 0; i < edges.length; i++) {
			var g = parser
					.read(edges[i].getElementsByTagName('wkt')[0].textContent);
			features.push(g);
		}
		result.addFeatures(features);
	}
}